package com.re6g3y.game.textureUitls;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.sun.media.jfxmediaimpl.MediaDisposer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多线程安全
 * 用于加载textrue 的组件，统一由该组件管理
 * load根据路径加载
 * get 根据名字获取
 */
public class TextureLoader implements MediaDisposer.Disposable{
    private Map<String,Texture> textureMap=new ConcurrentHashMap<String, Texture>();

    /**
     * 根据路径加载图片
     * @param path
     * @return
     */
    public Texture load(String path){
        FileHandle file=Gdx.files.internal(path);
        String name=file.name();
        Texture t=textureMap.get(name.substring(0,name.lastIndexOf(".")));
        if(t!=null)return t;
        t= new Texture(file);
        textureMap.put(name.substring(0,name.lastIndexOf(".")),t);
        return t;
    }

    /**
     * 获得图片
     * @param name
     * @return
     */
    public Texture get(String name){
        Texture t=textureMap.get(name);
        if(t==null)throw new RuntimeException("textrue is not loaded ,please load !");
        return t;
    }

    /**
     * 获得图片
     * @param name
     * @return
     */
    public void remove(String name){
        Texture t=textureMap.get(name);
        if(t==null)throw new RuntimeException("textrue is not loaded ,please load !");
        textureMap.remove(name);
        t.dispose();
    }

    @Override
    public void dispose() {
        for(Texture t:textureMap.values()){
            t.dispose();
        }
        textureMap.clear();
    }
}
